package com.wy.supermarket.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wy.supermarket.entity.Purchase;
import com.wy.supermarket.repository.PurchaseRepository;

@RestController
@RequestMapping("/purchase")
public class PurchaseController {
	@Autowired //自动装载
	private PurchaseRepository purchaseRepository;
	
	@GetMapping("/findAll/{page}/{size}")
	public Page<Purchase> findAll(@PathVariable("page") Integer page,@PathVariable("size") Integer size){
		Pageable pageable=PageRequest.of(page-1, size);
		return purchaseRepository.findAll(pageable);
	}
	
	@PostMapping("/addPurchase")
	public String addPurchase(@RequestBody Purchase purchase) {
		Purchase result=purchaseRepository.save(purchase);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@GetMapping("/findById/{pnum}")
	public Purchase findById(@PathVariable("pnum") Integer pnum) {
		return purchaseRepository.findById(pnum).get();
	}
	
	@PutMapping("/updatePurchase")
	public String updatePurchase(@RequestBody Purchase purchase) {
		Purchase result=purchaseRepository.save(purchase);
		if(result!=null) {
			return "sucess";
		}else {
			return "error";
		}
	}
	
	@DeleteMapping("/deleteById/{pnum}")
	public Purchase deleteById(@PathVariable("pnum") Integer pnum) {
		purchaseRepository.deleteById(pnum);
		return null;
	}

}

